<!-- ProfileView.vue -->
<template>
  <div>
    <!-- 引入头部导航栏 -->
    <Header />
    <div class="profile-container">
      <h1>个人中心</h1>

      <div class="profile-card">
        <!-- 头像展示 -->
        <div class="avatar-section">
          <img :src="getAvatarUrl(userInfo.avatar)" alt="用户头像" class="avatar">
          <button @click="showAvatarDialog = true" class="change-avatar-btn">更换头像</button>
        </div>

        <!-- 个人信息展示 -->
        <div class="profile-info">
          <div class="info-item">
            <span class="label">用户名：</span>
            <span class="value">{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <span class="label">性别：</span>
            <span class="value">{{ formatGender(userInfo.gender) }}</span>
          </div>
          <div class="info-item">
            <span class="label">手机号：</span>
            <span class="value">{{ userInfo.phone }}</span>
          </div>
          <div class="info-item">
            <span class="label">邮箱：</span>
            <span class="value">{{ userInfo.email }}</span>
          </div>
          <div class="info-item">
            <span class="label">真实姓名：</span>
            <span class="value">{{ userInfo.realName || '未设置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">年龄：</span>
            <span class="value">{{ userInfo.age || '未设置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">注册时间：</span>
            <span class="value">{{ formatDate(userInfo.createTime) }}</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button @click="openEditDialog" class="edit-btn">修改信息</button>
          <button @click="showChangePassword = true" class="password-btn">修改密码</button>
          <button @click="logout" class="logout-btn">退出登录</button>
        </div>

        <!-- 修改信息对话框 -->
        <el-dialog v-model="showEditDialog" :title="'修改个人信息'" width="600px">
          <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username" placeholder="请输入用户名" />
            </el-form-item>

            <el-form-item label="性别" prop="gender">
              <el-select v-model="editForm.gender" placeholder="请选择性别" class="w-full">
                <el-option label="未知" :value="0" />
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="editForm.phone" placeholder="请输入手机号" />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" placeholder="请输入邮箱" />
            </el-form-item>

            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="editForm.realName" placeholder="请输入真实姓名" />
            </el-form-item>

            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="editForm.age" :min="1" :max="120" placeholder="请输入年龄" />
            </el-form-item>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showEditDialog = false">取消</el-button>
              <el-button type="primary" @click="saveProfile" :loading="isSaving">
                保存
              </el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 更换头像对话框 -->
        <el-dialog v-model="showAvatarDialog" title="更换头像" width="400px">
          <div class="avatar-dialog-content">
            <input type="file" ref="avatarInput" @change="handleAvatarChange" accept="image/*" class="mb-4">
            <div class="dialog-actions">
              <el-button @click="showAvatarDialog = false">取消</el-button>
              <el-button type="primary" @click="uploadAvatar" :loading="isUploading">上传</el-button>
            </div>
          </div>
        </el-dialog>

        <!-- 修改密码对话框 -->
        <el-dialog v-model="showChangePassword" title="修改密码" width="500px">
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
            <el-form-item label="旧密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入旧密码" show-password />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
            </el-form-item>
          </el-form>

          <template #footer>
            <el-button @click="showChangePassword = false">取消</el-button>
            <el-button type="primary" @click="changePassword" :loading="isChangingPassword">确认修改</el-button>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '../../utils/request';
import Header from '@/components/Header.vue';

export default {
  name: 'ProfileView',
  components: {
    Header
  },
  setup() {
    const router = useRouter();
    const store = useStore();

    // 响应式数据
    const userInfo = ref({
      userId: null,
      username: '',
      gender: 0,
      phone: '',
      email: '',
      realName: '',
      age: null,
      avatar: '',
      createTime: null
    });

    const showEditDialog = ref(false);
    const showAvatarDialog = ref(false);
    const showChangePassword = ref(false);
    const isSaving = ref(false);
    const isUploading = ref(false);
    const isChangingPassword = ref(false);

    // 表单引用
    const editFormRef = ref();
    const passwordFormRef = ref();
    const avatarInput = ref();

    // 表单数据
    const editForm = ref({
      userId: '',
      username: '',
      gender: 0,
      phone: '',
      email: '',
      realName: '',
      age: null
    });

    const passwordForm = ref({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    });

    const avatarFile = ref(null);

    // 性别选项
    const genderOptions = [
      { label: '男', value: 1 },
      { label: '女', value: 2 },
      { label: '保密', value: 0 }
    ];

    // 表单验证规则
    const editRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      realName: [
        { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
      ],
      age: [
        { type: 'number', min: 1, max: 120, message: '年龄应在1-120之间', trigger: 'blur' }
      ]
    };

    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入旧密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.value.newPassword) {
              callback(new Error('两次输入的密码不一致'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ]
    };

    // 方法
    const formatGender = (gender) => {
      const genderMap = {
        0: '保密',
        1: '男',
        2: '女'
      };
      return genderMap[gender] || '未知';
    };

    const formatDate = (dateStr) => {
      if (!dateStr) return '未知';
      const date = new Date(dateStr);
      return date.toLocaleString();
    };

    const getAvatarUrl = (avatar) => {
      if (!avatar) return 'https://via.placeholder.com/150';
      
      // 如果已经是完整的URL，直接返回
      if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
        return avatar;
      }
      
      // 如果是相对路径，添加基础URL
      if (avatar.startsWith('/')) {
        return `http://localhost:8080${avatar}`;
      }
      
      return avatar;
    };

    const loadUserInfo = async () => {
      try {
        const currentUser = store.state.currentUser;

        // 确保store中存在有效的用户ID
        if (!currentUser || !currentUser.userId) {
          ElMessage.error('用户信息无效，请重新登录');
          store.dispatch('logout');
          router.push('/login');
          return;
        }

        // 使用有效的用户ID请求数据
        const response = await request.get(`/user/${currentUser.userId}`);

        if (response.data.status === 200) {
          const userData = response.data.user;
          userInfo.value = {
            userId: userData.userId,
            username: userData.username,
            gender: userData.gender || 0,
            phone: userData.phone || '',
            email: userData.email || '',
            realName: userData.realName || '',
            age: userData.age || null,
            avatar: userData.avatar || '',
            createTime: userData.createTime || null
          };

          // 更新store中的用户信息
          store.commit('setCurrentUser', {
            ...currentUser,
            ...userData
          });
        } else {
          throw new Error(response.data.msg || '获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        ElMessage.error('获取用户信息失败: ' + (error.response?.data?.msg || error.message));

        // 如果无法获取用户信息，清除无效的本地存储
        store.dispatch('logout');
        router.push('/login');
      }
    };

    const openEditDialog = () => {
      // 确保用户ID有效
      if (!userInfo.value.userId) {
        ElMessage.error('用户信息无效，请重新登录');
        store.dispatch('logout');
        router.push('/login');
        return;
      }

      // 将当前用户信息复制到编辑表单
      editForm.value = {
        userId: userInfo.value.userId,
        username: userInfo.value.username,
        gender: userInfo.value.gender,
        phone: userInfo.value.phone,
        email: userInfo.value.email,
        realName: userInfo.value.realName,
        age: userInfo.value.age
      };
      showEditDialog.value = true;
    };

    const saveProfile = async () => {
      try {
        // 验证表单
        await editFormRef.value.validate();

        // 确保用户ID有效
        if (!editForm.value.userId) {
          ElMessage.error('用户信息无效，请重新登录');
          store.dispatch('logout');
          router.push('/login');
          return;
        }

        isSaving.value = true;

        const updateData = {
          // 只发送后端需要的字段
          username: editForm.value.username,
          gender: editForm.value.gender,
          phone: editForm.value.phone,
          email: editForm.value.email,
          realName: editForm.value.realName,
          age: editForm.value.age
        };

        // 发送PUT请求更新用户信息
        const response = await request.put(`/user/${editForm.value.userId}`, updateData);

        if (response.data.status === 200) {
          await loadUserInfo();
          showEditDialog.value = false;
          ElMessage.success('个人信息更新成功');
        } else {
          throw new Error(response.data.msg || '更新失败');
        }
      } catch (error) {
        console.error('修改信息失败:', error);
        ElMessage.error('修改失败: ' + (error.response?.data?.msg || error.message));
      } finally {
        isSaving.value = false;
      }
    };

    const handleAvatarChange = (e) => {
      const file = e.target.files[0];
      if (file) {
        avatarFile.value = file;
      }
    };

    const uploadAvatar = async () => {
      if (!avatarFile.value) {
        ElMessage.warning('请选择头像文件');
        return;
      }

      try {
        isUploading.value = true;
        const formData = new FormData();
        formData.append('avatar', avatarFile.value);
        formData.append('userId', userInfo.value.userId);

        const response = await request.post('/user/avatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        if (response.data.status === 200) {
          userInfo.value.avatar = response.data.avatar;
          showAvatarDialog.value = false;
          avatarFile.value = null;
          if (avatarInput.value) {
            avatarInput.value.value = '';
          }
          ElMessage.success('头像上传成功');

          // 更新store中的用户信息
          const currentUser = store.state.currentUser;
          if (currentUser) {
            store.commit('setCurrentUser', {
              ...currentUser,
              avatar: response.data.avatar
            });
          }
        } else {
          throw new Error(response.data.msg || '上传失败');
        }
      } catch (error) {
        console.error('头像上传失败:', error);
        ElMessage.error('头像上传失败: ' + (error.response?.data?.msg || error.message));
      } finally {
        isUploading.value = false;
      }
    };

    const changePassword = async () => {
      try {
        // 验证表单
        await passwordFormRef.value.validate();
        isChangingPassword.value = true;

        // 确保用户ID有效
        if (!userInfo.value.userId) {
          ElMessage.error('用户信息无效，请重新登录');
          store.dispatch('logout');
          router.push('/login');
          return;
        }

        // 发送密码修改请求
        const response = await request.post(`/user/${userInfo.value.userId}/password`, {
          oldPassword: passwordForm.value.oldPassword,
          newPassword: passwordForm.value.newPassword
        });

        if (response.data.status === 200) {
          ElMessage.success('密码修改成功');
          showChangePassword.value = false;
          // 清空表单
          passwordForm.value = {
            oldPassword: '',
            newPassword: '',
            confirmPassword: ''
          };
        } else {
          throw new Error(response.data.msg || '密码修改失败');
        }
      } catch (error) {
        console.error('密码修改失败:', error);
        ElMessage.error('密码修改失败: ' + (error.response?.data?.msg || error.message));
      } finally {
        isChangingPassword.value = false;
      }
    };

    const logout = () => {
      ElMessageBox.confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('logout');
        router.push('/login');
        ElMessage.success('已退出登录');
      }).catch(() => {});
    };

    // 生命周期
    onMounted(() => {
      loadUserInfo();
    });

    return {
      userInfo,
      showEditDialog,
      showAvatarDialog,
      showChangePassword,
      isSaving,
      isUploading,
      isChangingPassword,
      editFormRef,
      passwordFormRef,
      avatarInput,
      editForm,
      passwordForm,
      avatarFile,
      genderOptions,
      formatGender,
      formatDate,
      getAvatarUrl,
      loadUserInfo,
      openEditDialog,
      saveProfile,
      handleAvatarChange,
      uploadAvatar,
      changePassword,
      logout,
      editRules,
      passwordRules
    };
  }
};
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.profile-card {
  background: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: relative;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #f0f0f0;
  margin-bottom: 15px;
}

.change-avatar-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.change-avatar-btn:hover {
  background-color: #40a9ff;
}

.profile-info {
  margin-bottom: 30px;
}

.info-item {
  margin-bottom: 15px;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.label {
  font-weight: bold;
  color: #555;
  display: inline-block;
  width: 100px;
}

.value {
  color: #333;
  flex: 1;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
}

button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.edit-btn {
  background-color: #1890ff;
  color: white;
}

.edit-btn:hover {
  background-color: #40a9ff;
}

.password-btn {
  background-color: #faad14;
  color: white;
}

.password-btn:hover {
  background-color: #ffc53d;
}

.logout-btn {
  background-color: #078fff;
  color: white;
}

.logout-btn:hover {
  background-color: #ff7875;
}

.avatar-dialog-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.dialog-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
  width: 100%;
}
</style>